from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status
from django.db.models import Q
from .models import SatelliteSchedule
from project_nav.models import Satellite
from datetime import datetime, timedelta
import json


@api_view(['POST'])
def get_constellation_schedule(request):
    """
    获取星座排程信息接口
    
    接受参数:
    - satedesc: 星座描述/卫星名称 (必需)
    - date: 日期 (可选，格式: YYYY-MM-DD)
    
    返回参数:
    - schedule_content: 排程内容
    - schedule_data: 排程日期
    """
    try:
        # 获取请求参数
        satedesc = request.data.get('satedesc')
        date = request.data.get('date')
        start_date = request.data.get('startDate')  # 从请求参数获取基准日期（备用）
        
        # 验证必需参数
        if not satedesc:
            return Response({
                'error': 'satedesc参数是必需的'
            }, status=status.HTTP_400_BAD_REQUEST)
        
        # 查找匹配的卫星
        satellites = Satellite.objects.filter(
            Q(name__icontains=satedesc) | 
            Q(description__icontains=satedesc)
        )
        
        # 调试信息：打印查询到的卫星
        print(f"查询参数: {satedesc}")
        print(f"找到的卫星数量: {satellites.count()}")
        for sat in satellites:
            print(f"卫星名称: {sat.name}, 描述: {sat.description}")
        
        if not satellites.exists():
            return Response({
                'error': f'未找到匹配的卫星: {satedesc}'
            }, status=status.HTTP_404_NOT_FOUND)
        
        # 获取所有匹配卫星的排程信息
        schedules = SatelliteSchedule.objects.filter(
            satellite__in=satellites
        ).select_related('satellite__group__project')
        
        # 调试信息：打印排程数据
        print(f"找到的排程数量: {schedules.count()}")
        for schedule in schedules:
            print(f"卫星: {schedule.satellite.name}, 排程信息类型: {type(schedule.schedule_info)}")
            if isinstance(schedule.schedule_info, list):
                print(f"排程信息长度: {len(schedule.schedule_info)}")
                for i, task in enumerate(schedule.schedule_info[:2]):  # 只打印前2个任务
                    print(f"任务 {i+1}: {task}")
            elif isinstance(schedule.schedule_info, dict):
                 print(f"排程信息字典键: {list(schedule.schedule_info.keys())}")
                 if 'tasks' in schedule.schedule_info:
                     print(f"任务数量: {len(schedule.schedule_info['tasks'])}")
                 elif 'scheduleItems' in schedule.schedule_info:
                     print(f"scheduleItems数量: {len(schedule.schedule_info['scheduleItems'])}")
                     for i, item in enumerate(schedule.schedule_info['scheduleItems'][:2]):  # 只打印前2个
                         print(f"scheduleItem {i+1}: {item}")
        
        if not schedules.exists():
            return Response({
                'error': f'未找到卫星 {satedesc} 的排程信息'
            }, status=status.HTTP_404_NOT_FOUND)
        
        # 初始化返回数据
        schedule_content = []
        schedule_data = []
        schedule_start_date = []
        schedule_end_date = []
        
        for schedule in schedules:
            satellite_name = schedule.satellite.name
            
            # 处理排程信息
            if isinstance(schedule.schedule_info, list):
                for task in schedule.schedule_info:
                    if isinstance(task, dict):
                        task_start = task.get('start_date', task.get('start_time', ''))
                        task_end = task.get('end_date', task.get('end_time', ''))
                        task_name = task.get('task_name', task.get('name', task.get('title', '未知任务')))
                        
                        # 如果没有直接的时间字段，尝试从startDay和duration计算
                        if not task_start and 'startDay' in task:
                            # 优先从排程信息中获取startDate，如果没有则使用请求参数中的startDate
                            schedule_start_date = None
                            if isinstance(schedule.schedule_info, dict) and 'startDate' in schedule.schedule_info:
                                schedule_start_date = schedule.schedule_info['startDate']
                            elif start_date:
                                schedule_start_date = start_date
                            
                            if schedule_start_date:
                                try:
                                    base_date = datetime.strptime(schedule_start_date, '%Y-%m-%d').date()
                                except ValueError:
                                    return Response({
                                        'error': 'startDate日期格式错误，请使用 YYYY-MM-DD 格式'
                                    }, status=status.HTTP_400_BAD_REQUEST)
                            else:
                                return Response({
                                    'error': '缺少基准日期startDate，请在前端设置开始日期或在请求中传递startDate参数'
                                }, status=status.HTTP_400_BAD_REQUEST)
                            
                            start_day = task.get('startDay', 0)
                            duration = task.get('duration', 0)
                            
                            # 计算实际开始和结束日期
                            actual_start_date = base_date + timedelta(days=start_day)
                            actual_end_date = base_date + timedelta(days=start_day + duration - 1) if duration > 0 else actual_start_date
                            
                            task_start = actual_start_date.strftime('%Y-%m-%d')
                            task_end = actual_end_date.strftime('%Y-%m-%d')
                        
                        # 提取日期部分（去掉时间）
                        start_date_only = task_start.split(' ')[0] if ' ' in task_start else task_start
                        end_date_only = task_end.split(' ')[0] if ' ' in task_end else task_end
                        
                        # 构建排程内容
                        content_item = {
                            'satellite_name': satellite_name,
                            'task_name': task_name,
                            'duration': task.get('duration', 0),
                            'start_time': task_start,
                            'end_time': task_end,
                            'equipment_info': task.get('equipment_info', {})
                        }
                        schedule_content.append(content_item)
                        
                        # 构建排程日期信息
                        if task_start:
                            date_item = {
                                'satellite_name': satellite_name,
                                'task_name': task_name,
                                'date': start_date_only,
                                'start_time': task_start,
                                'end_time': task_end
                            }
                            schedule_data.append(date_item)
                            
                            # 添加开始和结束日期
                            schedule_start_date.append(start_date_only)
                            schedule_end_date.append(end_date_only)
            
            elif isinstance(schedule.schedule_info, dict):
                # 如果是字典格式，处理tasks字段或scheduleItems字段
                tasks = schedule.schedule_info.get('tasks', [])
                if not tasks:
                    tasks = schedule.schedule_info.get('scheduleItems', [])
                for task in tasks:
                    if isinstance(task, dict):
                        task_start = task.get('start_date', task.get('start_time', ''))
                        task_end = task.get('end_date', task.get('end_time', ''))
                        task_name = task.get('task_name', task.get('name', task.get('title', '未知任务')))
                        
                        # 如果没有直接的时间字段，尝试从startDay和duration计算
                        if not task_start and 'startDay' in task:
                            # 优先从排程信息中获取startDate，如果没有则使用请求参数中的startDate
                            schedule_start_date_dict = None
                            if 'startDate' in schedule.schedule_info:
                                schedule_start_date_dict = schedule.schedule_info['startDate']
                            elif start_date:
                                schedule_start_date_dict = start_date
                            
                            if schedule_start_date_dict:
                                try:
                                    base_date = datetime.strptime(schedule_start_date_dict, '%Y-%m-%d').date()
                                except ValueError:
                                    return Response({
                                        'error': 'startDate日期格式错误，请使用 YYYY-MM-DD 格式'
                                    }, status=status.HTTP_400_BAD_REQUEST)
                            else:
                                return Response({
                                    'error': '缺少基准日期startDate，请在前端设置开始日期或在请求中传递startDate参数'
                                }, status=status.HTTP_400_BAD_REQUEST)
                            
                            start_day = task.get('startDay', 0)
                            duration = task.get('duration', 0)
                            
                            # 计算实际开始和结束日期
                            actual_start_date = base_date + timedelta(days=start_day)
                            actual_end_date = base_date + timedelta(days=start_day + duration - 1) if duration > 0 else actual_start_date
                            
                            task_start = actual_start_date.strftime('%Y-%m-%d')
                            task_end = actual_end_date.strftime('%Y-%m-%d')
                        
                        # 提取日期部分（去掉时间）
                        start_date_only = task_start.split(' ')[0] if ' ' in task_start else task_start
                        end_date_only = task_end.split(' ')[0] if ' ' in task_end else task_end
                        
                        content_item = {
                            'satellite_name': satellite_name,
                            'task_name': task_name,
                            'duration': task.get('duration', 0),
                            'start_time': task_start,
                            'end_time': task_end,
                            'equipment_info': task.get('equipment_info', {})
                        }
                        schedule_content.append(content_item)
                        
                        if task_start:
                            date_item = {
                                'satellite_name': satellite_name,
                                'task_name': task_name,
                                'date': start_date_only,
                                'start_time': task_start,
                                'end_time': task_end
                            }
                            schedule_data.append(date_item)
                            
                            # 添加开始和结束日期
                            schedule_start_date.append(start_date_only)
                            schedule_end_date.append(end_date_only)
        
        # 如果提供了日期参数，过滤结果
        if date:
            try:
                # 验证日期格式
                datetime.strptime(date, '%Y-%m-%d')
                
                # 过滤排程内容 - 匹配在指定日期范围内或在该日期开始工作的任务块
                filtered_content = []
                filtered_data = []
                filtered_start_dates = []
                filtered_end_dates = []
                
                for i, item in enumerate(schedule_content):
                    if item.get('start_time') and item.get('end_time'):
                        start_date_str = item['start_time'].split(' ')[0] if ' ' in item['start_time'] else item['start_time']
                        end_date_str = item['end_time'].split(' ')[0] if ' ' in item['end_time'] else item['end_time']
                        
                        try:
                            start_date_obj = datetime.strptime(start_date_str, '%Y-%m-%d').date()
                            end_date_obj = datetime.strptime(end_date_str, '%Y-%m-%d').date()
                            query_date_obj = datetime.strptime(date, '%Y-%m-%d').date()
                            
                            # 检查指定日期是否在任务的时间范围内，或者任务是否在指定日期开始
                            if (start_date_obj <= query_date_obj <= end_date_obj) or (start_date_obj == query_date_obj):
                                filtered_content.append(item)
                                if i < len(schedule_start_date):
                                    filtered_start_dates.append(schedule_start_date[i])
                                if i < len(schedule_end_date):
                                    filtered_end_dates.append(schedule_end_date[i])
                        except ValueError:
                            # 如果日期解析失败，跳过该项
                            continue
                
                for item in schedule_data:
                    if item.get('start_time') and item.get('end_time'):
                        start_date_str = item['start_time'].split(' ')[0] if ' ' in item['start_time'] else item['start_time']
                        end_date_str = item['end_time'].split(' ')[0] if ' ' in item['end_time'] else item['end_time']
                        
                        try:
                            start_date_obj = datetime.strptime(start_date_str, '%Y-%m-%d').date()
                            end_date_obj = datetime.strptime(end_date_str, '%Y-%m-%d').date()
                            query_date_obj = datetime.strptime(date, '%Y-%m-%d').date()
                            
                            # 检查指定日期是否在任务的时间范围内，或者任务是否在指定日期开始
                            if (start_date_obj <= query_date_obj <= end_date_obj) or (start_date_obj == query_date_obj):
                                filtered_data.append(item)
                        except ValueError:
                            # 如果日期解析失败，跳过该项
                            continue
                
                schedule_content = filtered_content
                schedule_data = filtered_data
                schedule_start_date = filtered_start_dates
                schedule_end_date = filtered_end_dates
                
            except ValueError:
                return Response({
                    'error': '日期格式错误，请使用 YYYY-MM-DD 格式'
                }, status=status.HTTP_400_BAD_REQUEST)
        
        # 构建返回数据列表
        data_list = []
        
        # 将收集到的数据转换为新格式
        for i, content in enumerate(schedule_content):
            task_item = {
                'schedule_content': content.get('task_name', '未知任务'),
                'schedule_start_data': schedule_start_date[i] if i < len(schedule_start_date) else '',
                'schedule_end_data': schedule_end_date[i] if i < len(schedule_end_date) else ''
            }
            
            # 只有提供了date参数时才添加schedule_data字段
            if date:
                task_item['schedule_data'] = date
            
            data_list.append(task_item)
        
        return Response({
            'msg': 'success',
            'code': '0',
            'data': data_list
        }, status=status.HTTP_200_OK)
        
    except Exception as e:
        return Response({
            'error': f'服务器内部错误: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)